package com.funsport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funsport.entity.Event;
import com.funsport.entity.EventSolitaire;
import com.funsport.mapper.EventSolitaireMapper;
import com.funsport.service.IEventService;
import com.funsport.service.IEventSolitaireService;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 活动接龙服务实现
 *
 * @author Fun-Sport Team
 */
@Slf4j
@Service
public class EventSolitaireServiceImpl extends ServiceImpl<EventSolitaireMapper, EventSolitaire> implements IEventSolitaireService {

    @Autowired
    private IEventService eventService;

    @Override
    @Transactional
    public boolean joinSolitaire(Long eventId, Long userId, String message) {
        try {
            // 检查活动是否存在并启用接龙
            Event event = eventService.getById(eventId);
            if (event == null) {
                log.warn("活动不存在: eventId={}", eventId);
                return false;
            }
            
            if (!Boolean.TRUE.equals(event.getEnableSolitaire())) {
                log.warn("活动未启用接龙功能: eventId={}", eventId);
                return false;
            }
            
            // 检查是否超过接龙截止时间
            if (event.getSolitaireCutoff() != null && LocalDateTime.now().isAfter(event.getSolitaireCutoff())) {
                log.warn("接龙已截止: eventId={}, cutoff={}", eventId, event.getSolitaireCutoff());
                return false;
            }
            
            // 检查是否已经参与接龙
            if (hasJoinedSolitaire(eventId, userId)) {
                log.warn("用户已参与接龙: eventId={}, userId={}", eventId, userId);
                return false;
            }

            // 创建接龙记录
            EventSolitaire solitaire = new EventSolitaire();
            solitaire.setEventId(eventId);
            solitaire.setUserId(userId);
            solitaire.setMessage(message);
            solitaire.setStatus("active");

            boolean success = this.save(solitaire);
            if (success) {
                log.info("用户参与接龙成功: eventId={}, userId={}", eventId, userId);
            }
            return success;

        } catch (Exception e) {
            log.error("参与接龙失败: eventId={}, userId={}", eventId, userId, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean cancelSolitaire(Long eventId, Long userId) {
        try {
            // 检查活动是否存在并启用接龙
            Event event = eventService.getById(eventId);
            if (event == null) {
                log.warn("活动不存在: eventId={}", eventId);
                return false;
            }
            
            // 检查是否超过接龙截止时间
            if (event.getSolitaireCutoff() != null && LocalDateTime.now().isAfter(event.getSolitaireCutoff())) {
                log.warn("接龙已截止，无法取消: eventId={}, cutoff={}", eventId, event.getSolitaireCutoff());
                return false;
            }
            
            LambdaQueryWrapper<EventSolitaire> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EventSolitaire::getEventId, eventId);
            wrapper.eq(EventSolitaire::getUserId, userId);
            wrapper.eq(EventSolitaire::getStatus, "active");

            EventSolitaire solitaire = this.getOne(wrapper);
            if (solitaire == null) {
                log.warn("未找到有效的接龙记录: eventId={}, userId={}", eventId, userId);
                return false;
            }

            solitaire.setStatus("cancelled");
            boolean success = this.updateById(solitaire);
            if (success) {
                log.info("用户取消接龙成功: eventId={}, userId={}", eventId, userId);
            }
            return success;

        } catch (Exception e) {
            log.error("取消接龙失败: eventId={}, userId={}", eventId, userId, e);
            return false;
        }
    }

    @Override
    public List<EventSolitaire> getEventSolitaires(Long eventId) {
        LambdaQueryWrapper<EventSolitaire> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventSolitaire::getEventId, eventId);
        wrapper.eq(EventSolitaire::getStatus, "active");
        wrapper.orderByAsc(EventSolitaire::getCreatedAt);
        return this.list(wrapper);
    }

    @Override
    public boolean hasJoinedSolitaire(Long eventId, Long userId) {
        LambdaQueryWrapper<EventSolitaire> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventSolitaire::getEventId, eventId);
        wrapper.eq(EventSolitaire::getUserId, userId);
        wrapper.eq(EventSolitaire::getStatus, "active");
        return this.count(wrapper) > 0;
    }

    @Override
    public int getSolitaireCount(Long eventId) {
        LambdaQueryWrapper<EventSolitaire> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EventSolitaire::getEventId, eventId);
        wrapper.eq(EventSolitaire::getStatus, "active");
        return Math.toIntExact(this.count(wrapper));
    }
}
